package com.ben.tcptester.tcpclient.netty;

import com.ben.tcptester.Entity.Client;
import com.ben.tcptester.Entity.Server;
import com.ben.tcptester.exception.ClientException;
import org.apache.log4j.Logger;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Peter on 2017/7/13.
 */
public class ServerRepository {
    private static Logger logger = Logger.getLogger(ServerRepository.class);
    public static Map<String, Server> connectMap = new ConcurrentHashMap<>();

    public static void add(String id, Server server) throws ClientException {
        if (connectMap.get(id) != null) {
            throw new ClientException(0, "服务器已存在（不能重复添加）");
        }
        connectMap.put(id, server);
    }

    public static Server get(String serverId) {
        return connectMap.get(serverId);
    }

    public static void remove(String serverId) {
        connectMap.remove(serverId);
    }

    public static void removeClient(String clientId) {
        Iterator<String> it = connectMap.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            Server srv = connectMap.get(key);
            boolean success = srv.removeClient(clientId);
            if (success) {
                logger.info("Remove client connect for clientId=" + clientId);
            }
        }
    }

    // 根据channelId （longTextString）查询该channel其对应的服务器
    public static Server getByChannelId(String channelId) {
        Iterator<String> it = connectMap.keySet().iterator();
        Client client = new Client(channelId);

        Server server = null;
        while (it.hasNext()) {
            String key = it.next();
            Server srv = connectMap.get(key);
            if (srv.getClients().contains(client)) {
                server = srv;
                break;
            }
        }

        return server;
    }
}
